// pages/event/index.js
const app = getApp();
Page({
    options: {
        styleIsolation: 'shared'
    },
    /**
     * 页面的初始数据
     */
    data: {
        CustomBar: app.globalData.CustomBar,
        winwidth: '',
        // swiper 属性
        vertical: false,
        interval: 3000,
        duration: 1000,
        x: 300,
        y: 300,
        // 项目类别
        typeList: ['全部', '便民利民', '扶贫帮困', '就业指导', '治安维稳', '卫生保健', '环境维护', '宣传教育', '文体娱乐', '助农增收', '心理咨询'],
        // 项目类别状态
        indexType: 0,
        // 项目状态
        indexStatus: 0,
        // 项目状态
        statusList: ['全部', '招募已结束', '招募中', '已结项'],
        // 发布日期状态
        dateStatus: 0,
        arrow_top: `cloud://cloud1-3gwgwntc19418eac.636c-cloud1-3gwgwntc19418eac-1312065174/images/icon/arrow-top.png`,
        arrow_bottom: `cloud://cloud1-3gwgwntc19418eac.636c-cloud1-3gwgwntc19418eac-1312065174/images/icon/arrow-bottom.png`,
        // 距离状态
        disStatus: 1,
        clientHeight: 469,
        // 吸住特效
        tabFixed: false,
        tabScrollTop: 0,
        headHeight: 0,
        headHeightString: '',
        //页码
        pageNum: 1,
        // 活动list
        activityList: [],
        faceImg: "cloud://cloud1-3gwgwntc19418eac.636c-cloud1-3gwgwntc19418eac-1312065174/orderimg/2022/06/30 01:10:04-782442.png",
        // 轮播图的list TODO 按照热度排序
        swiperList: [{
                title: '志愿者服务',
                image: 'cloud://cloud1-3gwgwntc19418eac.636c-cloud1-3gwgwntc19418eac-1312065174/orderimg/2022/06/30 18:57:40-889760.png',
            },
            {
                title: '志愿者在行动',
                image: 'cloud://cloud1-3gwgwntc19418eac.636c-cloud1-3gwgwntc19418eac-1312065174/orderimg/2022/06/30 18:48:38-632007.png',
            },
            {
                title: '实现共同富裕',
                image: 'cloud://cloud1-3gwgwntc19418eac.636c-cloud1-3gwgwntc19418eac-1312065174/orderimg/2022/06/30 01:10:04-782442.png',
            },
        ]
    },
    toSearch(){
      wx.navigateTo({
        url: '../Search/search',
      })
    },
    save(e) {
        // console.log('选中的状态值', this.data.indexStatus)
        // console.log('选中的类型', this.data.indexType)
        this.setData({
            modalName: null
        })
    },
    // 排序
    changeDateStatus() {
        console.log('oldList', this.data.activityList)
        let activityList = this.data.activityList
        if (this.data.dateStatus === 1) {
            activityList.sort(function (a, b) {
                return a.day - b.day
            })
            this.setData({
                dateStatus: 0,
                activityList: activityList
            })
        } else {
            activityList.sort(function (a, b) {
                return b.day - a.day
            })
            this.setData({
                dateStatus: 1,
                activityList: activityList
            })
        }
    },
    // distance
    changeDisStatus() {
        let activityList = this.data.activityList
        if (this.data.disStatus === 1) {
            activityList.sort(function (a, b) {
                return a.distance - b.distance
            })
            this.setData({
                disStatus: 0,
                activityList: activityList
            })
        } else {
            activityList.sort(function (a, b) {
                return b.distance - a.distance
            })
            this.setData({
                disStatus: 1,
                activityList: activityList
            })
        }
    },
    buttonType(e) {
        this.setData({
            indexType: e.currentTarget.dataset.index
        })
        // console.log('indexType',e.currentTarget.dataset.index)
    },
    // 选中项目状态
    buttonStatus(e) {
        this.setData({
            indexStatus: e.currentTarget.dataset.index
        })
        // console.log('indexStatus',e.currentTarget.dataset.index)
    },
    showModal(e) {
        this.setData({
            modalName: e.currentTarget.dataset.target
        })
    },
    hideModal(e) {
        this.setData({
            modalName: null
        })
    },
    gotoArticleDetail: function (event) {
        // console.log(event.currentTarget.dataset.articleid)
        // 当前要跳转到另一个界面，但是会保留现有界面
        wx.navigateTo({
            // url: `../eventPage/index?articleid=${event.currentTarget.dataset.articleid}`
            url: `../eventPageDetails/index?articleid=${event.currentTarget.dataset.articleid}`
        })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        const res = wx.getSystemInfoSync();
        let winwidth = res.windowWidth;
        this.setData({
            winwidth: winwidth
        });
        let that = this;
        // 动态获取scroll-view 高度
        wx.getSystemInfo({
            success: function (res) {
                let screenHeight = wx.getSystemInfoSync().windowHeight
                let screeWidth = wx.getSystemInfoSync().windowWidth
                that.setData({
                    x: 4 * screeWidth / 5,
                    y: screenHeight / 2
                })
                // console.log(screenHeight)
                let query = wx.createSelectorQuery().in(that);
                query.select('.event_head').boundingClientRect();
                query.exec(res => {
                    let h = res[0].height;
                    // console.log('组件头部高度',h+'px'+' !important')
                    // console.log(screenHeight - h)
                    that.setData({
                        clientHeight: screenHeight - h,
                        headHeight: h,
                        headHeightString: h + 'px' + ' !important'
                    })
                })

            }
        })
        // 登录成功获取所有活动
        wx.cloud.callFunction({
            name: 'volunteer',
            data: {
                type: 'getAllActivity',
                pageNum: that.data.activityList.length
            }
        }).then((resp) => {
            // console.log('获取的数据', resp.result.data)
            app.globalData.activityList = resp.result.data
            that.setData({
                activityList: resp.result.data,
                pageNum: that.data.activityList.length
            })
            wx.getLocation({
                type: 'wgs84',
                success(res) {
                    that.setData({
                        latitude: res.latitude,
                        longitude: res.longitude
                    })
                    that.Day()
                    wx.hideLoading();
                }
            })
        }).catch((e) => {
            console.log('出错了', e);
            wx.hideLoading();
        });


    },
    moveend(e) {
        let query = wx.createSelectorQuery();
        let queryString = '.movable-view';
        query.select(queryString).boundingClientRect();
        // 屏幕宽度
        let winwidth = this.data.winwidth;
        query.exec(function (res) {
            let ballwidth = res[0].width;
            // 移动过后悬浮球的位置
            let endPointleft = res[0].left;
            let endPointright = res[0].right;
            // 以屏幕中间为界划分屏幕左右两边
            let leftwin = endPointright < (winwidth / 2);
            if (leftwin == true) {
                console.log("我在左边")
            } else {
                console.log("我在右边")
            }
            if (endPointright >= winwidth || endPointleft <= 0) {
                console.log("我到边了")
            }
        })
    },
    balltap: function () {
        console.log("悬浮球被点击了")
        wx.navigateTo({
            url: '../submitEvent/index',
        })
    },


    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {
        var that = this;
        var query = wx.createSelectorQuery()
        query.select('.select').boundingClientRect()

        query.exec(function (res) {
            // console.log('组件到顶部距离', res[0].top - that.data.headHeight)
            that.setData({
                tabScrollTop: res[0].top - that.data.headHeight //根据实际需求加减值
            })
        })
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {
        //调用刷新时将执行的方法
        this.onRefresh();
    },
    //刷新
    onRefresh() {
        // //在当前页面显示导航条加载动画
        wx.showNavigationBarLoading();
        //显示 loading 提示框。需主动调用 wx.hideLoading 才能关闭提示框
        // wx.showLoading({
        //     title: '刷新中...',
        // })
        this.getData();

    },
    //网络请求，获取数据
    getData() {
        var that = this
        // 登录成功获取所有活动
        wx.cloud.callFunction({
            name: 'volunteer',
            data: {
                type: 'getAllActivity',
                pageNum: 0
            }
        }).then((resp) => {
            // console.log('获取的数据', resp.result.data)
            app.globalData.activityList = resp.result.data
            let activityList = resp.result.data
            for (let i = 0; i < activityList.length; i++) {
                let start = new Date().toISOString().substring(0, 10)
                let end = activityList[i].date
                let start_num = new Date(start.replace(/-/g, "/"))
                let end_num = new Date(end.replace(/-/g, "/"))
                let day = parseInt((end_num.getTime() - start_num.getTime()) / (1000 * 60 * 60 * 24))
                activityList[i].day = day
                // console.log(' activityList[i].day = day', activityList[i].day)
            }

            for (let i = 0; i < activityList.length; i++) {
                activityList[i].distance = that.getDistance(that.data.latitude, that.data.longitude, activityList[i].location.latitude, activityList[i].location.longitude);
                // console.log('activityList[i].distance', activityList[i].distance)
            }
            activityList.sort(function (a, b) {
                return a.day - b.day
            })
            that.setData({
                activityList: activityList
            })
            wx.stopPullDownRefresh();
            // wx.hideLoading();
        }).catch((e) => {
            console.log('出错了', e);
            wx.stopPullDownRefresh();
            // wx.hideLoading();
        });

    },
    // 计算剩余时间
    Day() {
        let activityList = this.data.activityList
        for (let i = 0; i < activityList.length; i++) {
            let start = new Date().toISOString().substring(0, 10)
            let end = activityList[i].date
            let start_num = new Date(start.replace(/-/g, "/"))
            let end_num = new Date(end.replace(/-/g, "/"))
            let day = parseInt((end_num.getTime() - start_num.getTime()) / (1000 * 60 * 60 * 24))
            activityList[i].day = day
            // console.log(' activityList[i].day = day', activityList[i].day)
        }

        for (let i = 0; i < activityList.length; i++) {
            activityList[i].distance = this.getDistance(this.data.latitude, this.data.longitude, activityList[i].location.latitude, activityList[i].location.longitude);
            // console.log('activityList[i].distance', activityList[i].distance)
        }

        this.setData({
            activityList: activityList
        })
    },
    // 计算距离函数
    Rad(d) {
        return d * Math.PI / 180.0;
    },
    /**
     * 经纬度计算两点的距离
     * @param {当前纬度}} lat1 
     * @param {当前经度} lng1 
     * @param {商家纬度} lat2 
     * @param {商家经度} lng2 
     */
    getDistance(lat1, lng1, lat2, lng2) {
        // console.log(lat1, lng1, lat2, lng2)
        var radLat1 = this.Rad(lat1);
        var radLat2 = this.Rad(lat2);
        var a = radLat1 - radLat2;
        var b = this.Rad(lng1) - this.Rad(lng2);
        var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
        s = s * 6378.137;

        s = s.toFixed(1)//保留小数
        // console.log('经纬度计算的距离:' + s)
        return s
    },
    gotoArticleDetail: function (event) {
        // 当前要跳转到另一个界面，但是会保留现有界面
        // console.log('跳转到xxx页面',event.currentTarget)
        wx.navigateTo({
            url: `../eventPageDetails/index?articleid=${event.currentTarget.dataset.articleid}`
        })
    },
    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {
        var that = this
        // console.log('上拉触底了')
        wx.showLoading({
            title: '加载中...',
        })
        //成功回调函数，具体需要根据业务需求设计分支结构，此处省略
        wx.cloud.callFunction({
            name: 'volunteer',
            data: {
                type: 'getAllActivity',
                pageNum: that.data.activityList.length
            }
        }).then((resp) => {
            // console.log('获取的数据', resp.result.data)

            //获取原始列表
            let activityList = that.data.activityList;
            //获取新列表
            let arr = resp.result.data;
            //新列表数据与原列表数据合并
            let newArr = activityList.concat(arr);
            // console.log('newArr',newArr)
            that.setData({
                activityList: newArr,
            })
            that.Day()
            app.globalData.activityList = newArr
            wx.hideLoading();
        }).catch((e) => {
            console.log('出错了', e);
            wx.hideLoading();
        });
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },
    // // 监听页面滚动
    onPageScroll: function (e) { // 页面滚动监听
        // console.log('滚动距离', e.scrollTop)
        // console.log('组件据顶部距离', this.data.tabScrollTop)
        this.setData({
            tabFixed: e.scrollTop >= this.data.tabScrollTop
        })
        // console.log(this.data.tabFixed, 'fixed');
    }
})